package com.cy.hui_jie_dan.controller.admin;


import com.cy.hui_jie_dan.comon.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "文件上传")
@RestController
public class updow {
    @Value("${imgPath.baseImgPath}")
    private String imgPath;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        if (filename != null) {
            String substring = filename.substring(filename.lastIndexOf("."));
            String fillName = UUID.randomUUID().toString()+substring;
            File file1 = new File(imgPath);
            if (!file1.exists()){
                file1.mkdir();
            }
            file.transferTo(new File(imgPath + fillName));
            return Result.success(fillName);
        }
        return Result.error("上传失败");
    }
    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void dowload(String name , HttpServletResponse response) throws IOException {
        //定义输入流
        FileInputStream fileInputStream = new FileInputStream(imgPath + name);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        if ((len = fileInputStream.read()) !=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }
}
